﻿using BlazorOrdering.Application;
using BlazorOrdering.Core;
using BlazorOrdering.Web.Entry.Areas.Identity.Data;
using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;



namespace BlazorOrdering.Web.Entry.Pages
{
    public partial class AddOrder 
    {
        [Inject] public MessageService MessageService { get; set; }
        [Inject] public UserManager<BlazorOrderingUser> UserManager { get; set; }
        [Inject] public AuthenticationStateProvider AuthenticationStateProvider { get; set; }
        [Inject] public IBoMenuService boMenuService { get; set; }


        private List<Order> Orders { get; set; } = new();
        private Order Order { get; set; } 
        private Message MessageElement { get; set; }


        /// <summary>
        /// 订单页的可选菜谱
        /// </summary>
        public List<BoMenu> boMenus { get; set; } = new();

        /// <summary>baise
        /// OnInitialized 方法
        /// </summary>
        protected override async Task OnInitializedAsync()
        {
            await MakeNewOrder();

            base.OnInitialized();
            await base.OnInitializedAsync();

        }

        private async Task MakeNewOrder()
        {
            // 初始化参数
            //创建订单
            Order = new Order();
            var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
            var user = authState.User;
            if (user.Identity.IsAuthenticated)
            {
                //下单人
                Order.UserName = UserManager.GetUserAsync(user).Result.CustomName;
            }
            //ChangWeek(bomenu.Day );
            //默认预定第二天的
            Order.Day = System.DateTime.Now.Date.AddDays(1);

            //根据日期获取可以使用的菜谱
            await DateValueChanged(System.DateTime.Now.Date.AddDays(1));
        }

        private async Task DateValueChanged(DateTime? d)
         {
            Order = new Order();
            var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
            var user = authState.User;
            if (user.Identity.IsAuthenticated)
            {
                //下单人
                Order.UserName = UserManager.GetUserAsync(user).Result.CustomName;
            }

            DateTime dt = (DateTime)d;
            Order.Day = dt.Date;

            //boMenus.Clear();
            //Order.OrderDetails.Clear();
            Task < List<BoMenu>> Menus=  boMenuService.GetMenusAsync(dt.Date);
            boMenus = Menus.Result;

            if (boMenus.Count>0)
            {
                OrderStatement orderStatement = new OrderStatement()
                {
                    Day = boMenus[0].Day,
                    Name = boMenus[0].Name,
                    Number = 1,
                    Price = boMenus[0].Price,
                    Type = boMenus[0].Type,
                    subtotal = boMenus[0].Price * 1
                };
                Order.OrderDetails.Add(orderStatement);
            }
            else
            {
                //ShowMessage("选中日期的菜谱尚未录入");
            }

            //return Task.CompletedTask;
        }

        private void AddorderStatement()
        {
            if (boMenus.Count>0)
            {

            
            if (boMenus.Count > Order.OrderDetails.Count)
            {
                OrderStatement orderStatement = new OrderStatement()
                {
                    Day = boMenus[Order.OrderDetails.Count].Day,
                    Name = boMenus[Order.OrderDetails.Count].Name,
                    Number = 1,
                    Price = boMenus[Order.OrderDetails.Count].Price,
                    Type = boMenus[Order.OrderDetails.Count].Type,
                    subtotal = boMenus[Order.OrderDetails.Count].Price * 1
                };
                Order.OrderDetails.Add(orderStatement);
            }
            else
            {
                OrderStatement orderStatement = new OrderStatement()
                {
                    Day = boMenus[0].Day,
                    Name = boMenus[0].Name,
                    Number = 1,
                    Price = boMenus[0].Price,
                    Type = boMenus[0].Type,
                    subtotal = boMenus[0].Price * 1
                };
                Order.OrderDetails.Add(orderStatement);
            }
            }
            else
            {
                ShowMessage("选定的日期无菜谱可选，请选择其他日期下单");
            }
        }

        private async Task<Task> OnValidSubmit(EditContext context)
        {
            //验证了后保存

            string result = orderService.AddOneOrder(this.Order);
            if (result == "ok")
            {
                Orders.Add(Order);
                ShowMessage("保存成功！");
                await MakeNewOrder(); //复位订单，为下一次点单准备
            }
            else
            {
                ShowMessage(result);
            }
            return Task.CompletedTask;
        }

        private Task OnInvalidSubmit(EditContext context)
        {
            ShowMessage("填写不符合规范，请检查");
            return Task.CompletedTask;
        }

        private void ShowMessage(string msg)
        {
            MessageElement.SetPlacement(Placement.Top);
            MessageService?.Show(new MessageOption()
            {
                Host = MessageElement,
                Content = msg
            });
        }

        private void CloseOneOrderStatement(string n)
        {
            //这里依据传递过来的name 移除list 中的项目
            //var name = n;
            for (int i = Order.OrderDetails.Count - 1; i >= 0; i--)
            {
                if (Order.OrderDetails[i].Name == n)
                {
                    Order.OrderDetails.Remove(Order.OrderDetails[i]);
                }
            }

            OrderCalculate();//移除了详单，要更新总价格

        }

        }
}
